<template>
  <Layout style="background:#fff;">
    <Row>
      <Col span="4">
      <Steps :current="stepCurrent" direction="vertical">
        <Step title="选择用户角色" />
        <Step title="填写用户信息" />
        <Step title="设置密码" />
      </Steps>
      </Col>
      <Col span="20">
      <!-- 选择用户组 -->
      <Form v-if="stepCurrent===0" ref="formRef0" :model="formData" :label-width="100" :rules="rules">
        <FormItem label="用户组：" prop="roleId">
          <Select v-model="formData.roleId" placeholder="选择用户组" @on-change="onRoleChange">
            <Option v-for="item in roleList" :key="item.id" :label="item.description" :value="item.id" />
          </Select>
        </FormItem>
      </Form>
      <!-- 填写用户信息 -->
      <div v-if="stepCurrent===1">
        <!-- ROLE_OPERATION 运营账号 -->
        <Form v-if="ROLE_OPERATION" ref="formRef1" :model="formData" :label-width="100" :rules="rules">
          <FormItem label="用户名：" prop="username">
            <Input v-model.trim="formData.username" placeholder="请输入用户名..." clearable />
          </FormItem>
          <FormItem label="姓名：" prop="name">
            <Input v-model.trim="formData.name" placeholder="请输入姓名..." clearable />
          </FormItem>
          <FormItem label="邮箱：" prop="email">
            <Input v-model.trim="formData.email" placeholder="请输入邮箱..." clearable />
          </FormItem>
          <FormItem label="电话：" prop="phone">
            <Input v-model.trim="formData.phone" placeholder="请输入电话..." clearable />
          </FormItem>
        </Form>
        <!-- ROLE_DEMO 演示账号 -->
        <Form v-if="ROLE_DEMO" ref="formRef1" :model="formData" :label-width="100" :rules="rules">
          <FormItem label="用户名：" prop="username">
            <Input v-model.trim="formData.username" placeholder="请输入用户名..." clearable />
          </FormItem>
        </Form>
        <!-- ROLE_PROVINCE 省级账号-->
        <Form v-if="ROLE_PROVINCE" ref="formRef1" :model="formData" :label-width="100" :rules="rules">
          <FormItem label="用户名：" prop="username">
            <Input v-model.trim="formData.username" placeholder="请输入用户名..." clearable />
          </FormItem>
          <FormItem label="一级地域：" prop="areaId">
            <Select v-model="formData.areaId" placeholder="选择所属地域">
              <Option v-for="(item,index) in firstRegionList" :key="item.id" :label="item.name" :value="item.id" />
            </Select>
          </FormItem>
        </Form>
        <!-- ROLE_CITY 市级账号 -->
        <Form v-if="ROLE_CITY" ref="formRef1" :model="formData" :label-width="100" :rules="rules">
          <FormItem label="用户名：" prop="username">
            <Input v-model.trim="formData.username" placeholder="请输入用户名..." clearable />
          </FormItem>
          <FormItem label="二级地域：" prop="areaId">
            <Row>
              <Col span="11">
              <Select v-model="provinceId" placeholder="请选择一级地域" @on-change="getSecondRigion">
                <Option v-for="(item,index) in firstRegionList" :key="item.id" :label="item.name" :value="item.id" />
              </Select>
              </Col>
              <Col span="2" style="text-align:center;">
              -
              </Col>
              <Col span="11">
              <Select v-model="formData.areaId" placeholder="请选择二级地域">
                <Option v-for="(item,index) in secondAreaList" :key="item.id" :label="item.name" :value="item.id" />
              </Select>
              </Col>
            </Row>
          </FormItem>
        </Form>
        <!-- ROLE_USER 企业账号 -->
        <Form v-if="ROLE_USER" ref="formRef1" :model="formData" :label-width="100" :rules="rules">
          <FormItem label="用户名：" prop="username">
            <Input v-model.trim="formData.username" placeholder="请输入用户名..." clearable />
          </FormItem>
          <FormItem label="所属企业：" prop="companyId">
            <Select v-model="formData.companyId" placeholder="选择所属企业">
              <Option v-for="item in companyList2" :key="item.id" :label="item.name" :value="item.id" />
            </Select>
          </FormItem>
          <FormItem label="姓名：" prop="name">
            <Input v-model.trim="formData.name" placeholder="请输入姓名..." clearable />
          </FormItem>
          <FormItem label="邮箱：" prop="email">
            <Input v-model.trim="formData.email" placeholder="请输入邮箱..." clearable />
          </FormItem>
          <FormItem label="电话：" prop="phone">
            <Input v-model.trim="formData.phone" placeholder="请输入电话..." clearable />
          </FormItem>
        </Form>
        <!-- ROLE_PLATFORM 代理商 -->
        <Form v-if="ROLE_PLATFORM" ref="formRef1" :model="formData" :label-width="100" :rules="rules">
          <FormItem label="用户名：" prop="username">
            <Input v-model.trim="formData.username" placeholder="请输入用户名..." clearable />
          </FormItem>
          <FormItem label="添加企业：" class="cover-ivu-form-item-lh" prop="companyIdList">
            <Treeselect v-model="formData.companyIdList" :options="treeData" :multiple="true" placeholder="选择代理企业" />
          </FormItem>
        </Form>
      </div>
      <!-- 设置密码 -->
      <Form v-if="stepCurrent===2" ref="formRef2" :model="formData" :label-width="100" :rules="rules">
        <FormItem label="密码：" prop="password">
          <Input v-model.trim="formData.password" type="password" placeholder="请输入密码..." clearable />
        </FormItem>
        <FormItem label="确认密码：" prop="password1">
          <Input v-model.trim="formData.password1" type="password" placeholder="确认密码..." clearable />
        </FormItem>
      </Form>
      </Col>
    </Row>
    <Row style="text-align:right; border-top:1px solid #e8eaec;padding-top:15px;">
      <Button @click="onCancel">取消</Button>
      <Button v-if="stepCurrent===2 || stepCurrent===1" @click="lastStep">上一步</Button>
      <Button v-if="stepCurrent===2" @click="onSubmit" type="primary">提交</Button>
      <Button v-if="stepCurrent===0 || stepCurrent===1" @click="nextStep">下一步</Button>
    </Row>
  </Layout>
</template>
<script>
import {
  getUserGroupList,
  addUser,
  getRegionByParams,
  getRegionAll,
  getCompanyListOfNew,
  postUserAgent
} from "@/api";
import {
  validateAddress,
  validateEmail,
  validateTelephone
} from "@/utils/rules";
import { validatePassWord, validateUserName } from "@/utils/validate";
import { buildTreeData } from "./utils";
export default {
  mounted() {
    this.getRoleList();
  },
  props: {
    userId: {
      type: String,
      default: ""
    }
  },
  data() {
    const validatePassCheck = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请在输入一遍密码"));
      } else if (value !== this.formData.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    const validatorCompanyIds = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error("至少选择一个代理企业"));
      } else {
        callback();
      }
    };
    return {
      formData: {
        roleId: null,
        username: null,
        password: null,
        password1: null,
        name: null,
        email: null,
        phone: null,
        areaId: "",
        companyId: "",
        companyIdList: []
      },
      provinceId: "",
      roleList: [],
      treeData: [],
      companyList: [],
      companyList2: [],
      firstRegionList: [],
      secondAreaList: [],
      stepCurrent: 0,
      ROLE_CITY: false, // 市级账号
      ROLE_OPERATION: false, // 运营账号,
      ROLE_DEMO: false, // 演示账号
      ROLE_PROVINCE: false, // 省级账号
      ROLE_USER: false, // 企业账号
      ROLE_PLATFORM: false, // 代理商账号
      rules: {
        roleId: [
          {
            required: true,
            message: "请选择用户组",
            trigger: "change"
          }
        ],
        username: [
          {
            required: "true",
            validator: validateUserName(
              "用户名",
              "用户名只能输入字母、数字、下划线、中划线并且不能小于4个字符"
            ),
            trigger: "blur"
          }
        ],
        companyIdList: [
          {
            required: true,
            validator: validatorCompanyIds,
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            validator: validatePassWord(
              "密码",
              "密码只能输入字母、数字、字母+数字"
            ),
            trigger: "blur"
          }
        ],
        password1: [
          {
            required: true,
            validator: validatePassCheck,
            trigger: "blur"
          }
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            validator: validateAddress(
              "姓名",
              "姓名只能输入中文、字母、数字、下划线和中划线"
            )
          }
        ],
        email: [
          {
            required: true,
            validator: validateEmail("邮箱", "邮箱地址无效"),
            trigger: "blur"
          }
        ],
        phone: [
          {
            required: true,
            validator: validateTelephone("电话", "手机号码格式不正确"),
            trigger: "blur"
          }
        ],
        areaId: [
          {
            required: true,
            message: "请选择所属地域",
            trigger: "change"
          }
        ],
        companyId: [
          {
            required: true,
            message: "请选择所属企业",
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    // 获取用户组列表
    getRoleList() {
      getUserGroupList().then(res => {
        if (res.code === 200) {
          this.roleList = res.data;
        }
      });
    },

    // 获取一级地域列表
    getFirstRigion(name) {
      const specialCity = ["北京市", "天津市", "重庆市", "上海市"];
      getRegionByParams({ type: 2 }).then(res => {
        if (res.code === 200) {
          if (name === "ROLE_CITY") {
            this.firstRegionList = res.data.filter(t => {
              if (!specialCity.includes(t.name)) return t;
            });
          } else {
            this.firstRegionList = res.data;
          }
        }
      });
    },

    // 获取二级地域
    getSecondRigion(provinceId) {
      const vm = this;
      vm.formData.areaId = "";
      const params = { provinceId };
      getRegionAll(params).then(res => {
        if (res.code === 200) {
          vm.secondAreaList = res.data.filter(t => t.belong !== "-");
        }
      });
    },

    // 获取企业列表，ROLE_USER 使用
    _getCompanyListOfNew() {
      getCompanyListOfNew({ size: 1000, page: 1 }).then(res => {
        if (res.code === 200) {
          this.companyList2 = res.data.list;
        }
      });
    },

    // 代理商获取企业列表
    getCompanyListForAgent() {
      getCompanyListOfNew({ size: 1000, page: 1 }).then(res => {
        if (res.code === 200) {
          const list = res.data.list;
          this.treeData = buildTreeData(list);
        }
      });
    },

    // 用户组 change 事件
    onRoleChange(id) {
      const vm = this;
      if (vm.ROLE_OPERATION) vm.ROLE_OPERATION = false;

      if (vm.ROLE_DEMO) vm.ROLE_DEMO = false;

      if (vm.ROLE_PLATFORM) vm.ROLE_PLATFORM = false;

      if (vm.ROLE_PROVINCE) vm.ROLE_PROVINCE = false;

      if (vm.ROLE_CITY) vm.ROLE_CITY = false;

      if (vm.ROLE_USER) vm.ROLE_USER = false;

      let name = vm.roleList.find(t => t.id === id).name;
      if (name === "ROLE_OPERATION") {
        vm.ROLE_OPERATION = true;
      } else if (name === "ROLE_DEMO") {
        vm.ROLE_DEMO = true;
      } else if (name === "ROLE_PROVINCE") {
        vm.getFirstRigion("ROLE_PROVINCE");
        vm.ROLE_PROVINCE = true;
      } else if (name === "ROLE_CITY") {
        vm.getFirstRigion("ROLE_CITY");
        vm.ROLE_CITY = true;
      } else if (name === "ROLE_USER") {
        vm._getCompanyListOfNew();
        vm.ROLE_USER = true;
      } else if (name === "ROLE_PLATFORM") {
        vm.getCompanyListForAgent();
        vm.ROLE_PLATFORM = true;
      }
    },

    // 下一步
    nextStep() {
      const vm = this;
      if (vm.stepCurrent === 0) {
        vm.$refs.formRef0.validate(valid => {
          if (valid) {
            if (vm.ROLE_PROVINCE || vm.ROLE_CITY) {
              vm.formData.areaId = "";
            }
            vm.stepCurrent = 1;
          }
        });
      } else if (vm.stepCurrent === 1) {
        vm.$refs.formRef1.validate(valid => {
          if (valid) {
            vm.stepCurrent = 2;
          }
        });
      }
    },

    // 上一步
    lastStep() {
      const vm = this;
      const { stepCurrent } = this;
      if (stepCurrent === 1) {
        this.$refs.formRef1.resetFields();
        this.stepCurrent = 0;
      } else if (stepCurrent === 2) {
        this.$refs.formRef2.resetFields();
        this.stepCurrent = 1;
      }
    },

    onSubmit() {
      this.$refs.formRef2.validate(valid => {
        if (valid) {
          this.fetchSubmit();
        }
      });
    },

    fetchSubmit() {
      const vm = this;
      const { ROLE_PLATFORM } = this;
      const params = JSON.parse(JSON.stringify(vm.formData));
      delete params.password1;
      // console.log(JSON.stringify(vm.formData))
      // return false
      if (!ROLE_PLATFORM) {
        addUser(params).then(res => {
          if (res.code == 200) {
            vm.$Message.success("操作成功");
            vm.$emit("save");
          }
        });
      } else {
        const companyIds = JSON.parse(
          JSON.stringify(vm.formData.companyIdList)
        );
        params["companyIds"] = companyIds.join(",");
        delete params.companyId;
        postUserAgent(params).then(res => {
          if (res.code === 200) {
            vm.$Message.success("操作成功");
            vm.$emit("save");
          } else {
            vm.$Message.error(res.message);
          }
        });
      }
    },

    // 取消
    onCancel() {
      this.$emit("off");
    }
  }
};
</script>
